import React, { useCallback, useState } from 'react';
import PropTypes from 'prop-types';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import { AtSearchBar } from 'taro-ui';
import HistoricalRecords from './historicalRecords';
import { saveKeyWordCache } from './util';
import './searchPage.scss';

/**
 * @name searchPage
 * @description 通用搜索页面
 */
const pageSize = 500;
function SearchPage(props) {
  const { renderItem, request, pageUniqueId } = props;
  const [keyWordValue, setKeyWordValue] = useState(undefined);
  const [list, setList] = useState([]);
  /**
   * @必填校验
   * */
  if(!pageUniqueId){
    console.error('pageUniqueId 不能为空，在SearchPage组件内部,否则会导致搜索历史覆盖!');
  }
  /**
   * @搜索
   * */
  const atSearchBarOnSubmit = useCallback(()=>{
    if (!keyWordValue) {
      Taro.showToast({
        title: '请输入搜索内容',
        icon: 'none',
      });
      setList([]);
      return;
    }
    /**
    * @保存搜索历史记录
    * */
    saveKeyWordCache(pageUniqueId,keyWordValue);
    /**
    * @模糊查询
    * */
    postData(keyWordValue);
  },[keyWordValue]);

  /**
   * @请求数据
   * */
  const postData = useCallback((keyword, pageIndex = 1)=>{
    const params = {
      condition: { keyword },
      pagingQuery: {
        pageIndex: pageIndex,
        pageSize
      },
    };
    const requestTrans = request(params);
    if (requestTrans.then){
      requestTrans.then((data)=>{
        if (data.success) {
          setList(data.models || []);
        }
      });
    } else {
      console.error('must return to promise');
    }

  },[]);

  /**
   * @点击tag
   * */
  const atTagOnClick = useCallback((value) => {
    setKeyWordValue(value);
    postData(value);
  }, []);

  const rootClass = classNames(
    'searchPage-wap',
    props.className
  )

  return (
    <View className={rootClass}>
      <AtSearchBar
        value={keyWordValue}
        onChange={setKeyWordValue}
        onConfirm={atSearchBarOnSubmit}
        onActionClick={atSearchBarOnSubmit}
      />
      {list.map((record)=>{
          return renderItem(record);
        })
      }
      {list.length == 0 && (
        <HistoricalRecords
          tagOnClick={atTagOnClick}
          pageUniqueId={pageUniqueId}
        />
      )}
    </View>
  );
}

SearchPage.defaultProps = {
  renderItem:(e)=>e,
  request:()=>{
    return Promise.resolve({});
  },
}

SearchPage.propTypes = {
  /**
   * @class
   * */
  className:PropTypes.string,
  /**
   * @列表项
   * */
  renderItem:PropTypes.any.isRequired,
  /**
   * @获取 dataSource 的方法
   * @ 需要返回一个promise
   * */
  request:PropTypes.any.isRequired,
  /**
   * @每个页面需要一个唯一标识
   * */
  pageUniqueId:PropTypes.any.isRequired,
}

export default SearchPage;
